package com.dk.wiki.service;

import com.dk.wiki.domain.Content;
import com.dk.wiki.domain.Doc;
import com.dk.wiki.domain.DocExample;
import com.dk.wiki.exception.BusinessException;
import com.dk.wiki.exception.BusinessExceptionCode;
import com.dk.wiki.mapper.ContentMapper;
import com.dk.wiki.mapper.DocMapper;
import com.dk.wiki.mapper.DocMapperCust;
import com.dk.wiki.req.DocQueryReq;
import com.dk.wiki.req.DocSaveReq;
import com.dk.wiki.resp.DocQueryResp;
import com.dk.wiki.resp.PageResp;
import com.dk.wiki.util.CopyUtil;
import com.dk.wiki.util.RedisUtil;
import com.dk.wiki.util.RequestContext;
import com.dk.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: ldk
 * 描述: TODO
 */
@Service
public class DocService {

    private static final Logger LOG = LoggerFactory.getLogger(DocService.class);

    @Resource // jdk所带的注解
    // @Autowired springboot所带的注解
    private DocMapper docMapper;

    @Autowired
    private DocMapperCust docMapperCust;

    @Resource
    private ContentMapper contentMapper;

    @Resource
     private SnowFlake snowFlake;

    @Resource
    public RedisUtil redisUtil;

    @Resource
    public WsService wsService;

    // @Resource
    // private RocketMQTemplate rocketMQTemplate;

    // 根据单一参数，返回查询数据
    // public List<Doc> list(String name){
    //     DocExample docExample = new DocExample();
    //     DocExample.Criteria criteria = docExample.createCriteria();
    //     criteria.andNameLike("%" + name + "%");
    //     List<Doc> docs = docMapper.selectByExample(docExample);
    //     return docs;
    // }

    public List<DocQueryResp> all(Long ebookId){
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        // DocExample.Criteria criteria = docExample.createCriteria();
        // criteria.andEbookIdEqualTo(ebookId);
        docExample.setOrderByClause("sort asc");
        List<Doc> docList = docMapper.selectByExample(docExample);

        // 列表复制
        List<DocQueryResp> docQueryRespList = CopyUtil.copyList(docList, DocQueryResp.class);
        return docQueryRespList;
    }

    public PageResp<DocQueryResp> list(DocQueryReq docQueryReq){
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        DocExample.Criteria criteria = docExample.createCriteria();

        PageHelper.startPage(docQueryReq.getPage(), docQueryReq.getSize());
        List<Doc> docList = docMapper.selectByExample(docExample);

        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getPages());
        // List<DocResp> docRespList = new ArrayList<>();
        // for (Doc doc : docsList) {
        //     // DocResp docResp = new DocResp();
        //     // // 逐一更行赋值，比较慢
        //     // // docResp.setId(doc.getId());
        //     // // 使用spring的BeanUtils工具
        //     // BeanUtils.copyProperties(doc, docResp);
        //     DocResp docResp = CopyUtil.copy(doc, DocResp.class);
        //     docRespList.add(docResp);
        // }

        // 列表复制
        List<DocQueryResp> docQueryRespList = CopyUtil.copyList(docList, DocQueryResp.class);
        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(docQueryRespList);
        return pageResp;
    }

    /**
     * 保存
     * @param docSaveReq
     */
    @Transactional
    public  void save(DocSaveReq docSaveReq){
        Doc doc = CopyUtil.copy(docSaveReq, Doc.class);
        Content content = CopyUtil.copy(docSaveReq, Content.class);
        if (ObjectUtils.isEmpty(docSaveReq.getId())){
            // 新增
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0);
            doc.setVoteCount(0);
            content.setId(doc.getId());
            contentMapper.insert(content);
            docMapper.insert(doc);
        }else{
            // 更新
            docMapper.updateByPrimaryKey(doc);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0){
                contentMapper.insert(content);
            }
        }
    }

    /**
     * 删除
     * @param id
     */
    public  void delete(Long id){
        docMapper.deleteByPrimaryKey(id);
    }

    /**
     * 删除
     * @param ids
     */
    public  void delete(List<String> ids){
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
        docMapper.deleteByExample(docExample);
    }

    public  String findContent(Long id){
        Content content = contentMapper.selectByPrimaryKey(id);
        // 文档阅读数+1
        docMapperCust.increaseViewCount(id);
        if(ObjectUtils.isEmpty(content)){
            return "";
        }else{
            return content.getContent();
        }
    }

    /**
     * 点赞
     * @param id 文档ID
     */
    public void vote(Long id){
        // docMapperCust.increaseVoteCount(id);
        //远程IP + doc.id 作为key, 24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id +"_" + ip, 5)){
            docMapperCust.increaseVoteCount(id);
        }else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

        // 推送消息
        Doc docDb = docMapper.selectByPrimaryKey(id);
        String logId = MDC.get("LOG_ID");
        wsService.sendInfo("【" + docDb.getName() + "】被点赞！",logId);
        // rocketMQTemplate.convertAndSend("VOTE_TOPIC", "【" + docDb.getName() + "】被点赞！");
    }

    public void updateEbookInfo(){
        docMapperCust.updateEbookInfo();
    }

}
